import router from '../router';
import store from '@/store';
import axios from 'axios'
import qs from 'qs'
import { getToken } from '@/utils'
const token = getToken()
export default async function request({
  api: {
    url,
    method = 'GET',
    timeout = 1000 * 60 * 15,
    dataType = 'json',
    headers = {},
    otherConfig = {}
  },
  params = {},
  urlParams = []
}) {
  if (urlParams && urlParams.length) {
    urlParams.forEach((key) => {
      url = url + '/' + key;
    });
  }
  const parsMap = Object.assign({}, params);
  for (const key in parsMap) {
    // 排除必传的空值参数 格式 [key.require]
    let keySets = key.split('.')
    // 删除value值为空的key
    if (parsMap[key] === '' && keySets !== 'require') {
      delete params[key];
    }
  }
  const config = {
    url,
    method,
    timeout,
    headers: {
      Authorization: token
        ? `Bearer ${token}`
        : ''
    }
  };

  if (config.method === 'GET' || config.method === 'get') {
    config.paramsSerializer = function (params) {
      return qs.stringify(params, { arrayFormat: 'repeat' });
    };
    config.params = params;
  } else {
    if (dataType === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(params);
    } else {
      config.data = params;
    }
  }

  if (JSON.stringify(headers) !== '{}') {
    config.headers = Object.assign(
      {},
      {
        ...config.headers,
        ...headers
      }
    );
  }

  if (JSON.stringify(otherConfig) !== '{}') {
    Object.assign(config, { ...otherConfig });
  }

  const result = {
    success: false,
    data: {},
    message: ''
  };
  try {
    const r = await axios(config);
    if (r.data) {
      if (
        (r.headers['content-type'] ===
          'application/vnd.ms-excel;charset=utf-8' ||
          r.headers['content-type'] ===
          'application/octet-stream;charset=utf-8') &&
        r.status === 200
      ) {
        result.success = true;
        result.data.file = r.data;
        result.data.mimeType = r.headers['content-type'];
        result.message = 'success';
      } else if (r.config.url === '/v2/authentication/figure/captcha') {
        result.success = true;
        result.data = r.data;
        result.message = r.data.msg;
      } else {
        switch (r.data.code) {
          case '0':
            result.success = true;
            result.data = r.data.data;
            result.message = r.data.msg;
            break;
          case '0001':
          default:
            result.message = r.data.msg;
        }
      }
    } else {
      console.warn('has no r.data');
    }
  } catch (e) {
    if (e.response) {
      switch (e.response.status) {
        case 401: {
          // 刷新token失效！
          result.message = '登录信息过期，请重新登录';
          // 清除token缓存
          sessionStorage.removeItem('token');
          router.push('/login');
          break;
        }
        case 403: // Token过期刷新token
          await store.dispatch('login/refreshToken', {
            refreshToken: store.state.login.refreshToken
          });
          break;
        case 404: // NotFound
          result.message = '访问地址不存在(404)';
          break;
        case 500:
        case 501:
        case 502:
          result.message = '服务器维护中，请稍后再试';
          break;
        default:
          result.message = e.response.statusText;
      }
    } else if (
      Object.prototype.hasOwnProperty.call(e, 'code') &&
      e.code === 'ECONNABORTED'
    ) {
      result.message = '请求超时';
    } else if (e.message && e.message === 'Network Error') {
      result.message = '无法连接到服务器';
    } else {
      if (e.message) {
        result.message = e.message;
      } else {
        console.error(e);
      }
    }
  }
  return result;
}